# -*- coding: utf-8 -*-
# @Time    : 2024/1/30 21:32
# @Author  : micah
# @File    : 14.使用asyncio完成英雄图片下载.py
# @Software: PyCharm


import os
import aiofile
import aiohttp
import asyncio


class HeroSkin:
    def __init__(self):
        self.json_url = 'https://pvp.qq.com/web201605/js/herolist.json'
        self.skin_url = 'https://game.gtimg.cn/images/yxzj/img201606/skin/hero-info/{}/{}-bigskin-{}.jpg'

        self.headers = {
            'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
        }

    async def get_image_content(self, session, e_name, c_name):
        for skin_id in range(1, 31):
            async with session.get(self.skin_url.format(e_name, e_name, skin_id), headers=self.headers) as response:
                if response.status == 200:
                    content = await response.read()
                    async with aiofile.async_open('./images/' + c_name + '-' + str(skin_id) + '.jpg', 'wb') as f:
                        await f.write(content)
                        print('保存成功:', c_name + '-' + str(skin_id))
                else:
                    break

    async def main(self):
        tasks = list()
        async with aiohttp.ClientSession() as session:
            async with session.get(self.json_url, headers=self.headers) as response:
                result = await response.json(content_type=None)
                for item in result:
                    e_name = item['ename']
                    c_name = item['cname']

                    coro_obj = self.get_image_content(session, e_name, c_name)
                    # await coro_obj
                    tasks.append(asyncio.create_task(coro_obj))

                await asyncio.wait(tasks)


if __name__ == '__main__':
    if not os.path.exists("./images"):
        os.mkdir("./images")

    hero_skin = HeroSkin()
    asyncio.run(hero_skin.main())
